package com.zhuiyun.educations.api.live.websocket;

import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName LiveWebsocket
 * @Description TODO
 * @Author cjl
 * @Date 2023/7/3 9:53
 **/
@Component
@ServerEndpoint(value = "/live/{id}/{userName}/{roomNum}")
public class LiveWebsocket {

    /**
     * 用来保存,用户的session
     */
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    /**
     * TODO OnOpen 当网络连接建立时触发该事件
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userName")String userName,@PathParam("roomNum")String roomNum){
        System.out.println(userName + "===========进入直播间=============================================");
        System.out.println(roomNum + "===========房间号=============================================");
        sessionMap.put(userName, session);
//        LiveDTO liveDTO = new LiveDTO();
//        liveDTO.setLiveRoom(roomNum);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("roomNum", roomNum);
        jsonObject.set("userName", userName);
        jsonObject.set("message", "来到直播间");
//        jsonObject.set("come", 1);
        sendAllMessage(jsonObject.toString());
    }

    /**
     * TODO OnMessage 当websocket接收到服务器发来的消息的时触发的事件，也是通信中最重要的一个监听事件
     */
    @OnMessage
    public void onMessage(Session session,@PathParam("userName")String userName,@PathParam("roomNum")String roomNum,String message) {
        System.out.println(userName + "===========发送消息=============================================");
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("roomNum", roomNum);
        jsonObject.set("userName", userName);
        jsonObject.set("message", message);
        jsonObject.set("come", 0);
        sendAllMessage(jsonObject.toString());
    }


    /**
     * TODO onClose 当websocket被关闭时触发该事件
     */
    @OnClose
    public void onClose(Session session,@PathParam("id") String id){

    }

    /**
     * TODO OnError 当网络发生错误时触发该事件
     */
    @OnError
    public void onError(Session session,Throwable error,@PathParam("id") String id) {

    }

    /**
    * TODO 将当前在线人数发送给每个浏览器（用户）
    */
    private void sendAllMessage(String message){
        try {
            for(Session session : sessionMap.values()){
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
